package com.xhwl.centiotdata.suppliersystem.guangtuo.alarmhost.websocket;

import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.util.Map;
import java.util.concurrent.ExecutorService;

/**
 * @author zhouyongzhou
 * @date 2023/04/26  13:51
 * Websocket基础类
 */
@Slf4j
public class BaseWebsocketClient extends WebSocketClient {
    private URI uri;
    /**
     * 客户端连接状态
     */
    private boolean isConnect = false;

    private ExecutorService workPoolScheduler;

    public BaseWebsocketClient(URI serverUri, Map<String, String> httpHeaders,
                               ExecutorService workPoolScheduler) {
        super(serverUri, new Draft_6455(), httpHeaders, 0);
        this.uri = serverUri;
        this.workPoolScheduler = workPoolScheduler;
    }

    @Override
    public void onOpen(ServerHandshake serverHandshake) {
    }

    @Override
    public void onMessage(String s) {
    }

    /***检测到连接关闭之后，会更新连接状态以及尝试重新连接***/
    @Override
    public void onClose(int i, String s, boolean b) {
        log.info("onClose()------URL:{} onError ------{}", uri, b);
        setConnectState(false);
        reConnect();
    }

    /***检测到错误，更新连接状态***/
    @Override
    public void onError(Exception e) {
        log.info("onError()------URL:{} onError ------{}", uri, e);
        setConnectState(false);
    }

    public void setConnectState(boolean isConnect) {
        this.isConnect = isConnect;
    }


    /**
     * 重连
     */
    public void reConnect() {
        workPoolScheduler.execute(() -> {
            Thread.currentThread().setName("ReconnectThread-" + Thread.currentThread().getId());
            try {
                Thread.sleep(10000);
                log.info("URL:{}----重连开始", uri);
                if (isConnect) {
                    log.info("UURL:{}---- 重连停止", uri);
                    return;
                }
                this.reconnect();
                log.info("URL:{}----重连结束", uri);
            } catch (Exception e) {
                log.info("URL:{}---重连失败", uri);
            }
        });
    }
}

